package com.smartcanteen.user.controller.admin;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.smartcanteen.result.Result;
import com.smartcanteen.security.utils.SecurityUtils;
import com.smartcanteen.system.api.domain.SysUser;
import com.smartcanteen.system.api.model.LoginUser;
import com.smartcanteen.user.domain.entity.Business;
import com.smartcanteen.user.service.IBusinessService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

@RestController("adminShopController") // 重命名，防止两个端admin、user的ShopController冲突
@RequestMapping("/admin/shop")
@Slf4j
public class ShopController {

    @Autowired
    private IBusinessService businessService;

    public static final String KEY = "SHOP_STATUS";


    /**
     * 设置店铺状态,同时添加商家至商家表中
     *
     * @param status
     * @return
     */
    @PostMapping("/status/{status}")
    public Result setStatus(@PathVariable Integer status) {
        // 获取当前的用户信息
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getSysUser();
        // 将前端传过来的状态值存到loginUser.status中
        sysUser.setStatus(String.valueOf(status));
        // 在数据库中查询当前用户是否有信息
        Business business = businessService.selectBusinessById(sysUser.getUserId());
        // 如果数据库中有信息，则进行删除
        if (business != null) {
            businessService.deleteBusinessById(business.getId());
        }
        businessService.insertBusiness(sysUser);
        return Result.success();

    }

    @GetMapping("/status")
    public Result<Integer> getStatus() {
        // 获取当前的用户信息
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getSysUser();
        // 在数据库中查询当前用户是否有信息
        Business business = businessService.selectBusinessById(sysUser.getUserId());
        if (business != null) {
            // 如果不为空，返回状态值
            return Result.success(Math.toIntExact(business.getStatus()));
        } else {
            // 如果为空，返回0
            return Result.success(0);
        }
    }
}
